package com.ccx.coachsite.bus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;

import com.ccx.coachsite.downloadmgr.ImageCacheTool;
import com.ccx.coachsite.http.BaseResp;
import com.ccx.coachsite.http.HttpRequest;
import com.ccx.coachsite.http.UrlConfig;

public class TutorialProvider {

	private static TutorialProvider mInstance;

	public static TutorialProvider getInstance() {
		if (mInstance == null)
			mInstance = new TutorialProvider();
		return mInstance;
	}

	private String lastErrorMessage;

	public String getLastErrorMessage() {
		return lastErrorMessage;
	}

	public List<TutorialPageInfo> getTutorials() {
		List<TutorialPageInfo> androidPages = getTutorials(1);
		if (androidPages == null)
			return null;
		List<TutorialPageInfo> iphonePages = getTutorials(2);
		if (iphonePages == null)
			return null;
		for (TutorialPageInfo tutorialPageInfo : iphonePages) {
			androidPages.add(tutorialPageInfo);
		}
		List<TutorialPageInfo> wpPages = getTutorials(3);
		if (wpPages == null)
			return null;
		for (TutorialPageInfo tutorialPageInfo : wpPages) {
			androidPages.add(tutorialPageInfo);
		}
		return androidPages;
	}

	public List<TutorialInfo> search(String keyword, int page) {
		try {
			lastErrorMessage = "";
			ArrayList<TutorialInfo> tutorials = new ArrayList<TutorialInfo>();
			String url = String
					.format(UrlConfig
							.getUrlByKey(UrlConfig.SearchTutorialUrlKey), page);
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("keyword", keyword);
			BaseResp br = HttpRequest.DoHttpRepuestPost(url, params);
			if (br.isSuccess()) {
				JSONObject responseObject = new JSONObject(br.getResponse());
				JSONArray tutorialList = responseObject
						.optJSONArray("tutorial");
				for (int i = 0; i < tutorialList.length(); i++) {
					JSONObject tutorialObj = tutorialList.optJSONObject(i);
					TutorialInfo tutorial = new TutorialInfo();
					tutorial.setId(tutorialObj.optInt("id"));
					tutorial.setTitle(tutorialObj.optString("name"));
					tutorial.setImageUrl(tutorialObj.optString("tutorialUrl"));
					tutorial.setDate(tutorialObj.optString("createdWhen"));
					tutorials.add(tutorial);
				}
				return tutorials;
			}
			if (br.getErrorCode().equals("841")
					|| br.getErrorCode().equals("842"))
				lastErrorMessage = "搜索关键词里不能包含特殊字符";
		} catch (Exception e) {
			lastErrorMessage = e.getMessage();
		}
		return null;
	}

	public boolean loadDetail(Context context, TutorialInfo tutorial) {
		try {
			lastErrorMessage = "";
			Account account = AccountMgr.readAccountInfo(context);
			String url = String.format(
					UrlConfig.getUrlByKey(UrlConfig.GetTutorialDetailUrlKey),
					tutorial.getId(), account.getUserId());
			BaseResp br = HttpRequest.DoHttpRequest(url);
			if (br.isSuccess()) {
				JSONArray detailArray = new JSONArray(br.getResponse());
				if (detailArray == null || detailArray.length() <= 0)
					return false;
				JSONObject data = detailArray.optJSONObject(0);
				tutorial.setTitle(data.optString("name"));
				tutorial.setContent(data.optString("guid"));
				tutorial.setCategoryId(data.optInt("pageType"));
				// String apkUrl = data.optString("apkUrl");
				// if (!TextUtils.isEmpty(apkUrl) && !"null".equals(apkUrl))
				// tutorial.setApkUrl(apkUrl);
				JSONArray apkArray = data.optJSONArray("apkList");
				if (apkArray != null && apkArray.length() > 0) {
					int apkId = apkArray.getJSONObject(0).optInt("id", -1);
					if (apkId >= 0)
						tutorial.setApkId(apkId);
				}
				int collectedFlag = data.optInt("collection", 0);
				tutorial.setFavour(collectedFlag != 0);
				return true;
			} else {
				lastErrorMessage = br.getDesc();
			}
		} catch (Exception e) {
			lastErrorMessage = e.getMessage();
		}
		return false;
	}

	public boolean collectFavour(Context context, TutorialInfo tutorial) {
		try {
			lastErrorMessage = "";
			Account account = AccountMgr.readAccountInfo(context);
			String url = String.format(
					UrlConfig.getUrlByKey(UrlConfig.TutorialCollectFavour),
					account.getUserId(), tutorial.getId());
			BaseResp br = HttpRequest.DoHttpRequest(url);
			lastErrorMessage = br.getDesc();
			return br.isSuccess();
		} catch (Exception e) {
			lastErrorMessage = e.getMessage();
		}
		return false;
	}

	private List<TutorialPageInfo> getTutorials(int type) {
		try {
			lastErrorMessage = "";
			ArrayList<TutorialPageInfo> pages = new ArrayList<TutorialPageInfo>();
			String url = String
					.format(UrlConfig.getUrlByKey(UrlConfig.GetTutorialUrlKey),
							type, 0);
			BaseResp br = HttpRequest.DoHttpRequest(url);
			if (br.isSuccess()) {
				JSONObject responseObject = new JSONObject(br.getResponse());
				JSONArray tutorialList = responseObject.optJSONArray("list");
				TutorialPageInfo page = null;
				for (int i = 0; i < tutorialList.length(); i++) {
					JSONObject tutorialObj = tutorialList.optJSONObject(i);
					if (page == null || page.getPageIndex() != i / 5) {
						page = new TutorialPageInfo();
						page.setPageIndex(i / 5);
						page.setPageType(type);
						ArrayList<TutorialInfo> pageTutorialList = new ArrayList<TutorialInfo>();
						page.setTutorialList(pageTutorialList);
						pages.add(page);
					}
					TutorialInfo tutorial = new TutorialInfo();
					tutorial.setId(tutorialObj.optInt("id"));
					tutorial.setTitle(tutorialObj.optString("name"));
					tutorial.setImageUrl( ImageCacheTool.encodeImgUrl(tutorialObj.optString("tutorialUrl")) );
					tutorial.setDate(tutorialObj.optString("createdWhen"));
					tutorial.setCategoryId(type);
					page.getTutorialList().add(tutorial);
				}
				return pages;
			}
		} catch (Exception e) {
			lastErrorMessage = e.getMessage();
		}
		return null;
	}
}
